//
//  BAAlbumDetailCellNode.m
//  BabyAlbum
//
//  Created by master on 17/2/15.
//  Copyright © 2017年 master. All rights reserved.
//

#import "BAAlbumDetailCellNode.h"
#import "BAAlbumListLayout.h"
#import "BAImageNode.h"
#import "BAHeaderNode.h"
#import "SuPhotoPicker.h"
#import "TZImagePickerController.h"
#import "MWPhotoBrowser.h"
#import "BAVideoHeader.h"

@interface BAAlbumDetailCellNode () <ASEditableTextNodeDelegate,ASCollectionDataSource, ASCollectionDelegateFlowLayout, BACollectionViewLayoutDelegate,ASCollectionViewLayoutInspecting,TZImagePickerControllerDelegate,UIActionSheetDelegate,MWPhotoBrowserDelegate>

@property (nonatomic, strong) BAAlbumModel *albumModel;
@property (nonatomic, strong) BAAlbumModel *albumModel_Origin;


@property (nonatomic, strong) NSMutableArray<BAAlbumItem *> *resourceList;
@property (nonatomic, strong) NSMutableArray <MWPhoto *> *photos;

//@property (nonatomic, strong) ASImageNode *imageNode;
//@property (nonatomic, strong) ASTextNode *dateNode;
//@property (nonatomic, strong) ASDisplayNode *lineNode;
//@property (nonatomic, strong) ASTextNode *detailNode;
@property (nonatomic, strong) ASButtonNode *returnButton;
@property (nonatomic, strong) ASButtonNode *editButton;
@property (nonatomic, strong) ASEditableTextNode *titleNode;
@property (nonatomic, strong) ASCollectionNode *collectionNode;

@property (nonatomic, strong) ASCellNode *headerNode;

@property (nonatomic, strong) UILongPressGestureRecognizer *longPress;

@end

@implementation BAAlbumDetailCellNode


- (instancetype)initWithData:(BAAlbumModel *)model{
    if(self = [super init]) {
        _isEditing = NO;
        self.albumModel = model;
//        self.albumModel.desc = [self.albumModel.desc stringByAppendingFormat:@"%d",arc4random()%10000000];
        self.albumModel_Origin = model;
        [self viewInit];
        // 临时解决需要解决多线程造成的数据库崩溃
//        dispatch_async(dispatch_get_main_queue(), ^{
//
//        });
    }
    return self;
}


- (void)viewInit {
    
    self.returnButton = [[ASButtonNode alloc] init];
    [self.returnButton setImage:[UIImage imageNamed:@"return.png"] forState:UIControlStateNormal];
    self.returnButton.imageNode.contentMode = UIViewContentModeScaleAspectFit;
    [self.returnButton addTarget:self action:@selector(back) forControlEvents:ASControlNodeEventTouchUpInside];
    [self addSubnode:self.returnButton];
    
    self.titleNode = [[ASEditableTextNode alloc] init];
    NSAttributedString *string = [NSAttributedString attributedStringWithString:self.albumModel.title fontSize:15 color:RGBWhite(140)];
    self.titleNode.placeholderEnabled = YES;
    self.titleNode.maximumLinesToDisplay = 1;
    self.titleNode.attributedPlaceholderText = [NSAttributedString attributedStringWithString:@"为当前相册添加标题" fontSize:15 color:RGBWhite(180)];
    self.titleNode.attributedText = string;
    self.titleNode.delegate = self;
    
    
    [self addSubnode:self.titleNode];
    
    self.editButton = [[ASButtonNode alloc] init];
    [self.editButton setImage:[UIImage imageNamed:@"edit_end.png"] forState:UIControlStateNormal];
    self.editButton.imageNode.contentMode = UIViewContentModeScaleAspectFit;
    [self.editButton addTarget:self action:@selector(save) forControlEvents:ASControlNodeEventTouchUpInside];
    self.editButton.hidden = YES;
    
    [self addSubnode:self.editButton];
    
    BAAlbumListLayout *layout = [[BAAlbumListLayout alloc] init];
    layout.numberOfColumns = 2;
    //    [self reloadData];
    
    layout.headerHeight = [BAHeaderNode calculteHeightWithData:self.albumModel];
    
    self.collectionNode = [[ASCollectionNode alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight) collectionViewLayout:layout];
    self.collectionNode.dataSource = self;
    self.collectionNode.delegate = self;
    [self addSubnode:self.collectionNode];
    
    dispatch_async(dispatch_get_main_queue(), ^{
        self.collectionNode.view.showsHorizontalScrollIndicator = NO;
        self.collectionNode.view.showsVerticalScrollIndicator = NO;
        self.collectionNode.view.layoutInspector = self;
        
        self.collectionNode.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        self.collectionNode.backgroundColor = [UIColor whiteColor];
        
        [_collectionNode registerSupplementaryNodeOfKind:UICollectionElementKindSectionHeader];
        [self.collectionNode setNeedsLayout];

    });
}

- (UILongPressGestureRecognizer *)longPress {
    if(!_longPress) {
        _longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(showEdit:)];
        _longPress.minimumPressDuration = 1;

    }
    return _longPress;
}

- (void)didLoad {
    [super didLoad];
    self.resourceList = [NSMutableArray arrayWithArray:[self.albumModel fetchResourceList]];
    self.titleNode.textView.textAlignment = NSTextAlignmentCenter;
    self.titleNode.textView.userInteractionEnabled = _isEditing;
    if(!_isEditing) {
        [self.view addGestureRecognizer:self.longPress];
    }
}

- (ASLayoutSpec *)layoutSpecThatFits:(ASSizeRange)constrainedSize
{
    _collectionNode.style.preferredSize = CGSizeMake(constrainedSize.max.width, kScreenHeight - 64);
    _editButton.style.maxSize = CGSizeMake(30, 15);
    _returnButton.style.maxSize = CGSizeMake(30, 15);
    _titleNode.style.preferredSize = CGSizeMake(150, 20); // 60

    CGFloat hor_interval = (kScreenWidth - (40*2) - (10 *2) - _titleNode.style.preferredSize.width) / 2;

    ASRelativeLayoutSpec *sepc_return = [ASRelativeLayoutSpec relativePositionLayoutSpecWithHorizontalPosition:ASRelativeLayoutSpecPositionCenter verticalPosition:ASRelativeLayoutSpecPositionStart sizingOption:ASRelativeLayoutSpecSizingOptionMinimumHeight child:_returnButton];
    ASRelativeLayoutSpec *sepc_edit = [ASRelativeLayoutSpec relativePositionLayoutSpecWithHorizontalPosition:ASRelativeLayoutSpecPositionCenter verticalPosition:ASRelativeLayoutSpecPositionEnd sizingOption:ASRelativeLayoutSpecSizingOptionDefault child:_editButton];
    ASRelativeLayoutSpec *sepc_title = [ASRelativeLayoutSpec relativePositionLayoutSpecWithHorizontalPosition:ASRelativeLayoutSpecPositionStart verticalPosition:ASRelativeLayoutSpecPositionStart sizingOption:ASRelativeLayoutSpecSizingOptionMinimumHeight child:_titleNode];
    
    
    
    ASStackLayoutSpec *stack = [ASStackLayoutSpec stackLayoutSpecWithDirection:ASStackLayoutDirectionHorizontal spacing:hor_interval justifyContent:ASStackLayoutJustifyContentStart alignItems:ASStackLayoutAlignItemsCenter children:@[sepc_return,sepc_title,sepc_edit]];
    
    ASStackLayoutSpec *ver  = [ASStackLayoutSpec stackLayoutSpecWithDirection:ASStackLayoutDirectionVertical spacing:10 justifyContent:ASStackLayoutJustifyContentStart alignItems:ASStackLayoutAlignItemsCenter children:@[stack,_collectionNode]];

    return [ASInsetLayoutSpec insetLayoutSpecWithInsets:UIEdgeInsetsMake(30, 0, 0, 0) child:ver];
}

// 存在闪屏
- (void)setIsEditing:(BOOL)isEditing {
    if(_isEditing != isEditing) {
        _isEditing = isEditing;
        if(_isEditing) {
//            [[XYKeyboardHelper sharedInstance] enableKeyboardHelper];
//            [self setUpForDismissKeyboard];
            self.titleNode.textView.userInteractionEnabled = YES;
            self.editButton.hidden = NO;
            [self.view removeGestureRecognizer:self.longPress];
        }else {
            [self.view endEditing:YES];
            self.titleNode.textView.userInteractionEnabled = NO;
            self.editButton.hidden = YES;
            [self.view addGestureRecognizer:self.longPress];
        }
        [self reloadData];
    }
}



- (void)layout {
    [super layout];
}

- (void)showEdit:(UILongPressGestureRecognizer *)ges {
    if (ges.state == UIGestureRecognizerStateBegan) {
        UIActionSheet *actionsheet = [[UIActionSheet alloc] initWithTitle:@"编辑" delegate:self cancelButtonTitle:@"取消当前操作" destructiveButtonTitle: nil otherButtonTitles:@"编辑当前相册",@"删除当前相册", nil];
        [actionsheet showInView:KEYWINDOW];
    }
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    switch (buttonIndex) {
        case 0:
            self.isEditing = YES;
            break;
        case 1:
        {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"确定删除" message:@"是否要删除该相册" delegate:nil cancelButtonTitle:@"再想想" otherButtonTitles:@"确定", nil];
            [alert uxy_handlerClickedButton:^(UIAlertView *alertView, NSInteger btnIndex) {
                switch (btnIndex) {
                    case 0:
                        break;
                    case 1: {
                        [self deleteAlbum];
                    }break;
                    default:
                        break;
                }
            }];
            [alert show];
        }
            break;
        case 2:
            
            break;
        default:
            break;
    }
}



- (void)reloadData {
    [self.collectionNode reloadData];
}

- (BOOL)editableTextNode:(ASEditableTextNode *)editableTextNode shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    if(editableTextNode.textView.text.length > 20) {
        return NO ;
    }
    return YES && _isEditing;
}

- (void)back {
    [self.manager.navigationController popViewControllerAnimated:YES];
}


- (void)deleteAlbum {
    [BADB deleteAlbum:self.albumModel];
    [BAALBUM_DATA reloadData];
    [self back];
}
//TODO: 2.22 写视频的存储及读取测试
- (void)save {
    if(![self.albumModel.cover isSetted]) {
        [MBProgressHUD showError:@"没有封面"];
        return;
    }
    if(![self.albumModel.title length]) {
        [MBProgressHUD showError:@"没有标题"];
        return;
    }
    
//    self.albumModel.desc = self.de
    
    [BADB updateAlbumDataWithModel:self.albumModel];
    [self back];
    [BAALBUM_DATA reloadData];
}

#pragma mark - ASCollectionView Data Source

- (ASCellNodeBlock)collectionNode:(ASCollectionNode *)collectionNode nodeBlockForItemAtIndexPath:(NSIndexPath *)indexPath;
{
    if(_isEditing && indexPath.row == self.resourceList.count) {
        UIImage *image = [UIImage imageNamed:@"add_btn.png"];
        return ^{
            BAImageNode *imageNode = [[BAImageNode alloc] initWithImage:image editMode:NO];
//            [imageNode setDeleteBlock:^(NSIndexPath *indexPath) {
//                [self.imageList removeObject:image];
//                self.albumModel.imageList = [self.imageList copy];
//
//                [self.collectionNode deleteItemsAtIndexPaths:@[indexPath]];
//            }];
            return imageNode;
        };

    } else {
        BAAlbumItem *item = self.resourceList[indexPath.row];
        
        return ^{
            BAImageNode *imageNode;
            if(item.type == BAResourceTypeImage) {
                BAAlbumImageItem *imageItem = (BAAlbumImageItem *)item;
                imageNode = [[BAImageNode alloc] initWithImage:imageItem.image editMode:_isEditing];
                [imageNode setDeleteBlock:^(NSIndexPath *indexPath) {
                    [self.resourceList removeObject:item];
                    _albumModel.resourceList = self.resourceList;
                    [self.collectionNode deleteItemsAtIndexPaths:@[indexPath]];
                }];

            } else {
                BAAlbumVideoItem *videoItem = (BAAlbumVideoItem *)item;
                imageNode = [[BAImageNode alloc] initWithImage:[videoItem.video getThumbnailImage] editMode:_isEditing];
                [imageNode setDeleteBlock:^(NSIndexPath *indexPath) {
                    [self.resourceList removeObject:item];
                    _albumModel.resourceList = self.resourceList;
                    [self.collectionNode deleteItemsAtIndexPaths:@[indexPath]];
                }];

            }
            return imageNode;
        };

    }
    
}


- (NSInteger)collectionNode:(ASCollectionNode *)collectionNode numberOfItemsInSection:(NSInteger)section
{
    return _isEditing ? self.resourceList.count + 1 : self.resourceList.count;
}

- (NSInteger)numberOfSectionsInCollectionNode:(ASCollectionNode *)collectionNode
{
    return 1;
}


- (ASSizeRange)collectionView:(ASCollectionView *)collectionView constrainedSizeForNodeAtIndexPath:(NSIndexPath *)indexPath
{
    BAAlbumListLayout *layout = (BAAlbumListLayout *)[collectionView collectionViewLayout];
    return ASSizeRangeMake(CGSizeZero, [layout itemSizeAtIndexPath:indexPath]);
}



- (ASSizeRange)collectionView:(ASCollectionView *)collectionView constrainedSizeForSupplementaryNodeOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    BAAlbumListLayout *layout = (BAAlbumListLayout *)[collectionView collectionViewLayout];
    return ASSizeRangeMake(CGSizeZero, [layout headerSizeForSection:indexPath.section]);
}

- (ASScrollDirection)scrollableDirections
{
    return ASScrollDirectionVerticalDirections;
}

/**
 * Asks the inspector for the number of supplementary views for the given kind in the specified section.
 */
- (NSUInteger)collectionView:(ASCollectionView *)collectionView supplementaryNodesOfKind:(NSString *)kind inSection:(NSUInteger)section
{
    return [kind isEqualToString:UICollectionElementKindSectionHeader] ? 10 : 0;
}

- (ASCellNode *)collectionNode:(ASCollectionNode *)collectionNode nodeForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.row == 0) {
        
        self.headerNode = [[self.albumModel.cover.type == BAResourceTypeVideo ? [BAVideoHeader class] : [BAHeaderNode class]  alloc] initWithData:self.albumModel isEdit:_isEditing selectPhotoBlock:^{
            
            if([self.titleNode.textView isFirstResponder]) {
                [self.view endEditing:YES];
                
            }
            TZImagePickerController *imagePicker = [[TZImagePickerController alloc] initWithMaxImagesCount:1 delegate:self];
            imagePicker.allowCrop = YES;
            [imagePicker setDidFinishPickingVideoHandle:^(UIImage * image, id obj) {
//                if(photos.count) {
                [self getVideoFromPHAsset:obj data:^(AVURLAsset *asset) {
                    self.albumModel.cover = [BAAlbumVideoItem itemWithVideoAsset:asset];
//                    self.albumModel.isVideoCover = YES;
                    [self reloadData];
                }];

            }];
            [imagePicker setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> * photos, NSArray *assets, BOOL isSelectOrigin) {
                if(photos.count) {
//                    self.albumModel.isVideoCover = NO;
                    self.albumModel.cover = [BAAlbumImageItem itemWithImage:[photos firstObject]];
                    [self reloadData];
                }

            }];
             [KEYWINDOW.rootViewController presentViewController:imagePicker animated:YES completion:nil];
        } textChangeBlock:^(NSString *text) {
            self.albumModel.desc = text;
        }];
        return self.headerNode;

    }
    return [[ASCellNode alloc] init];
}


- (CGSize)collectionView:(ASCollectionNode *)collectionNode layout:(UICollectionViewLayout *)collectionViewLayout originalItemSizeAtIndexPath:(NSIndexPath *)indexPath
{
    ASCellNode *cellNode = [collectionNode nodeForItemAtIndexPath:indexPath];
    if ([cellNode isKindOfClass:[BAImageNode class]]) {
        CGSize size =  [(BAImageNode *)cellNode calculatedSize];
        return size;
    }
    return CGSizeMake(120, 120);
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    return nil;
}

- (void)collectionNode:(ASCollectionNode *)collectionNode didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if(_isEditing && indexPath.row == self.resourceList.count) {
        if([self.titleNode.textView isFirstResponder]) {
            [self.view endEditing:YES];
        }
        TZImagePickerController *imagePicker = [[TZImagePickerController alloc] initWithMaxImagesCount:1 delegate:self];
        imagePicker.allowCrop = YES;
        [imagePicker setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> * photos, NSArray *assets, BOOL isSelectOrigin) {
            if(photos.count) {
                BAAlbumImageItem *imageItem = [BAAlbumImageItem itemWithImage:[photos firstObject]];
                [self.resourceList addObject:imageItem];
                self.albumModel.resourceList = [self.resourceList copy];
//                [self reloadData];
                [self.collectionNode insertItemsAtIndexPaths:@[[NSIndexPath indexPathForRow:self.albumModel.resourceList.count - 1 inSection:0]]];

            }
            
        }];
        [imagePicker setDidFinishPickingVideoHandle:^(UIImage * image, id obj) {
            [self getVideoFromPHAsset:obj data:^(AVURLAsset *asset) {
                BAAlbumVideoItem *videoItem = [BAAlbumVideoItem itemWithVideoAsset:asset];
                [self.resourceList addObject:videoItem];
                self.albumModel.resourceList = [self.resourceList copy];
                [self.collectionNode insertItemsAtIndexPaths:@[[NSIndexPath indexPathForRow:self.albumModel.resourceList.count - 1 inSection:0]]];
            }];
            
        }];
        [KEYWINDOW.rootViewController presentViewController:imagePicker animated:YES completion:nil];
    }
    else if(!_isEditing){
        [self showPhotoBrowerWithIndex:indexPath.row];
    }
}


- (void)editableTextNodeDidUpdateText:(ASEditableTextNode *)editableTextNode {
    self.albumModel.title = editableTextNode.textView.text;
}


#pragma show and hide the keyboard
- (void)setUpForDismissKeyboard {
    NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
    UITapGestureRecognizer *singleTapGR =
    [[UITapGestureRecognizer alloc] initWithTarget:self
                                            action:@selector(tapAnywhereToDismissKeyboard:)];
    NSOperationQueue *mainQuene =[NSOperationQueue mainQueue];
    [nc addObserverForName:UIKeyboardWillShowNotification
                    object:nil
                     queue:mainQuene
                usingBlock:^(NSNotification *note){
                    [self.view addGestureRecognizer:singleTapGR];
                }];
    [nc addObserverForName:UIKeyboardWillHideNotification
                    object:nil
                     queue:mainQuene
                usingBlock:^(NSNotification *note){
                    [self.view removeGestureRecognizer:singleTapGR];
                }];
}

- (void)tapAnywhereToDismissKeyboard:(UIGestureRecognizer *)gestureRecognizer {
    //此method会将self.view里所有的subview的first responder都resign掉
    [self.view endEditing:YES];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    [self.view endEditing:YES];
}

- (void)showPhotoBrowerWithIndex:(NSInteger)index {
    // Create array of MWPhoto objects
    self.photos = [NSMutableArray array];
    
    for(BAAlbumItem *item in self.resourceList) {
        if(item.type == BAResourceTypeImage) {
            BAAlbumImageItem *imageItem = (BAAlbumImageItem *)item;
            [self.photos addObject:[MWPhoto photoWithImage:imageItem.image]];
        } else if(item.type == BAResourceTypeVideo) {
            BAAlbumVideoItem *videoItem = (BAAlbumVideoItem *)item;

            [self.photos addObject:[MWPhoto videoWithURL:videoItem.video.URL]];
        }
    }
    MWPhotoBrowser *browser = [[MWPhotoBrowser alloc] initWithDelegate:self];
    
    // Set options
    browser.displayActionButton = YES; // Show action button to allow sharing, copying, etc (defaults to YES)
    browser.displayNavArrows = NO; // Whether to display left and right nav arrows on toolbar (defaults to NO)
    browser.displaySelectionButtons = NO; // Whether selection buttons are shown on each image (defaults to NO)
    browser.zoomPhotosToFill = YES; // Images that almost fill the screen will be initially zoomed to fill (defaults to YES)
    browser.alwaysShowControls = NO; // Allows to control whether the bars and controls are always visible or whether they fade away to show the photo full (defaults to NO)
    browser.enableGrid = YES; // Whether to allow the viewing of all the photo thumbnails on a grid (defaults to YES)
    browser.startOnGrid = NO; // Whether to start on the grid of thumbnails instead of the first photo (defaults to NO)
    browser.autoPlayOnAppear = NO; // Auto-play first video
    
    // Customise selection images to change colours if required
    browser.customImageSelectedIconName = @"ImageSelected.png";
    browser.customImageSelectedSmallIconName = @"ImageSelectedSmall.png";
    
    // Optionally set the current visible photo before displaying
    [browser setCurrentPhotoIndex:index];
    
    // Present
    [self.manager.navigationController pushViewController:browser animated:YES];
    
    // Manipulate
    [browser showNextPhotoAnimated:YES];
    [browser showPreviousPhotoAnimated:YES];
//    [browser setCurrentPhotoIndex:10];
}


- (NSUInteger)numberOfPhotosInPhotoBrowser:(MWPhotoBrowser *)photoBrowser {
    return self.photos.count;
}

- (id <MWPhoto>)photoBrowser:(MWPhotoBrowser *)photoBrowser photoAtIndex:(NSUInteger)index {
    if (index < self.photos.count) {
        return [self.photos objectAtIndex:index];
    }
    return nil;
}

- (void)getVideoFromPHAsset:(PHAsset *)asset data:(void (^)(AVURLAsset *asset))block {
    PHVideoRequestOptions *option = [PHVideoRequestOptions new];

    [[PHImageManager defaultManager] requestAVAssetForVideo:asset options:option resultHandler:^(AVAsset * _Nullable asset, AVAudioMix * _Nullable audioMix, NSDictionary * _Nullable info) {
        dispatch_async(dispatch_get_main_queue(), ^{
            AVURLAsset * ass= (AVURLAsset *)asset;
//            NSData *data = [NSData dataWithContentsOfURL:ass.URL];
            block(ass);
        });
    }];
}
@end
